/**
 * 
 */
package arisufascion.com.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import arisufascion.com.AbstractActivity;
import arisufascion.com.R;
import arisufascion.com.adapter.BannerGalleryAdapter;
import arisufascion.com.adapter.ListNewProductAdapter;
import arisufascion.com.compone.LoadMoreListView;
import arisufascion.com.compone.LoadMoreListView.OnLoadMoreListener;
import arisufascion.com.compone.PagingView;
import arisufascion.com.compone.SwipeableGallery;
import arisufascion.com.constant.Constants;
import arisufascion.com.handler.ProductHandler;
import arisufascion.com.handler.ServiceHandler;
import arisufascion.com.model.Product;
import arisufascion.com.network.RequestTask;
import arisufascion.com.tabs.TabGroupActivity;

/**
 * @author Kelvin
 * 
 */
public class ActivityHome extends AbstractActivity implements
		OnItemSelectedListener {
	private int page = 1;
	private LayoutInflater inflater;
	View footer;
	private boolean isLoading = true;
	private ProgressDialog dialog;
	private LoadMoreListView myproduct_list;
	private ListNewProductAdapter mAdapter;
	private List<Product> products = new ArrayList<Product>();

	public SwipeableGallery bannerGallery;
	public PagingView bannerPagingView;
	private Handler handler = new Handler();
	private Runnable runable = null;
	private static final int SCROLL_INTERVAL = 3000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		findViewById(R.id.btn_menu).setOnClickListener(onClick);
		findViewById(R.id.btn_privacy).setOnClickListener(onClick);
		findViewById(R.id.btn_wholesale).setOnClickListener(onClick);
		findViewById(R.id.btn_shipping).setOnClickListener(onClick);

		inflater = LayoutInflater.from(this);
		footer = inflater.inflate(R.layout.loadmore, null);

		myproduct_list = (LoadMoreListView) findViewById(R.id.list_new_products);

		myproduct_list.setOnLoadMoreListener(loadMoreListener);
		myproduct_list.addFooterView(footer);

		myproduct_list.setOnItemClickListener(onItemClick);

		initView();

		loadRecomendContents();
		startAutoBannerGalleryScroll();

		if (isNetworkAvailable()) {
			if (products.size() < 1) {
				new getProductLatesFromServer(page).execute();
			}
		} else {
			Toast.makeText(self, "Please On wifi or 3G.", Toast.LENGTH_LONG)
					.show();
			self.finish();
		}

	}

	public void initView() {
		this.bannerGallery = (SwipeableGallery) findViewById(R.id.bannerGallery);
		// bannerGallery.setOnItemSelectedListener(this);
		this.bannerPagingView = (PagingView) findViewById(R.id.bannerPagingView);
		bannerGallery.setOnItemSelectedListener(this);
	}

	OnLoadMoreListener loadMoreListener = new OnLoadMoreListener() {

		@Override
		public void onLoadMore() {
			page++;
			new getProductLatesFromServer(page);
		}
	};

	public class getProductLatesFromServer extends
			AsyncTask<Void, Void, List<Product>> {

		int page = 1;

		public getProductLatesFromServer(int page) {
			this.page = page;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Show Dialog
			dialog = new ProgressDialog(getParent());
			dialog.setMessage("Fetching data...");
			dialog.show();
		}

		@Override
		protected List<Product> doInBackground(Void... params) {

			String url = Constants.SERVER_URL_LATES_PRODUCT;
			url = String.format(url, Constants.SERVER_API_KEY, page);

			Log.d("get mon an ", url);

			String json = RequestTask.getJsonFromUrl(url);

			ServiceHandler service = new ServiceHandler();
			ProductHandler mProductHandler = service.getProductLatests(json);

			return mProductHandler.getData();

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(List<Product> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			// Dismiss Dialog
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}

			if (result != null) {
				if (products == null || products.isEmpty()) {
					footer.setVisibility(VISIBLE);
					products = result;
					int size = result.size();

					if (size < 15) {
						footer.setVisibility(GONE);
						myproduct_list.setOnLoadMoreListener(null);
					}

					products = result;
					mAdapter = new ListNewProductAdapter(self, products);
					myproduct_list.setAdapter(mAdapter);

				} else {
					int size = result.size();
					if (size < 15) {
						footer.setVisibility(GONE);
						myproduct_list.setOnLoadMoreListener(null);
					}
					mAdapter.addItem(result);
					myproduct_list.onLoadMoreComplete();
				}
			} else {
				footer.setVisibility(GONE);
				myproduct_list.setOnLoadMoreListener(null);
			}
		}
	}

	OnItemClickListener onItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long arg3) {
			view.setSelected(true);

			Product pro = (Product) parent.getAdapter().getItem(position);

			Bundle bundle = new Bundle();
			bundle.putParcelable(PRODUCT, pro);
			Intent intent_product = new Intent(self, Activity_Detail.class);

			intent_product.putExtras(bundle);

			// startActivity(intent_product);

			TabGroupActivity tabGroupActivity = (TabGroupActivity) getParent();
			tabGroupActivity.startChildActivity("Activity_Detail",
					intent_product);
		}
	};

	public void loadRecomendContents() {
		// バナーギャラリーを初期化します。
		List<Integer> promotionItem = new ArrayList<Integer>(6);
		promotionItem.add(0, R.drawable.banner1);
		promotionItem.add(1, R.drawable.banner2);
		promotionItem.add(2, R.drawable.banner3);
		promotionItem.add(0, R.drawable.banner1);
		promotionItem.add(1, R.drawable.banner2);
		promotionItem.add(2, R.drawable.banner3);

		BannerGalleryAdapter bannerAdapter = new BannerGalleryAdapter(this,
				promotionItem);
		this.bannerGallery.setSpacing(-1);
		this.bannerGallery.setAdapter(bannerAdapter);
		this.bannerPagingView.build(6);
	}

	private void startAutoBannerGalleryScroll() {
		if (runable == null) {
			runable = new Runnable() {
				public void run() {
					int currentPosition = bannerGallery
							.getSelectedItemPosition();
					int childCount = bannerPagingView.getChildCount();

					if (currentPosition < childCount - 1) {
						bannerGallery.scrollToNextItem();
						bannerPagingView.setPosition(currentPosition + 1);
					} else {
						bannerGallery.setSelection(0);
						bannerPagingView.setPosition(0);
					}

					handler.postDelayed(runable, SCROLL_INTERVAL);
				}
			};
		}

		handler.postDelayed(runable, SCROLL_INTERVAL);
	}

	public void onItemSelected(AdapterView<?> adapter, View view, int position,
			long l) {
		if (adapter.getId() == R.id.bannerGallery) {
			this.bannerPagingView.setPosition(position);
		}
	}

	private void stopAutoBannerGalleryScroll() {
		if (runable != null) {
			this.handler.removeCallbacks(runable);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}
}